package com.third.clock.manager;

import android.app.Notification;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.third.clock.R;
import com.third.clock.common.Contants;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import java.lang.reflect.Field;


/**
 * Created by Administrator on 2018/7/23 0023.
 */

public class UmengManager implements IBaseManager,IUmengRegisterCallback {

    private Context context;

    private PushAgent mPushAgent;

    public  String mDevicetoken;

    private Handler handler;

    private static UmengManager mUmengManager;

    private UmengManager(Context context){
        this.context=context.getApplicationContext();
    }

    public static UmengManager getInstance(Context context){
        if(mUmengManager==null){
            synchronized (UmengManager.class){
                if(mUmengManager==null){
                    mUmengManager=new UmengManager(context);
                }
            }
        }
        return mUmengManager;
    }

    @Override
    public void onCreate() {
        try {
            Class<?> aClass = Class.forName("com.umeng.commonsdk.UMConfigure");
            Field[] fs = aClass.getDeclaredFields();
            for (Field f:fs){
                Log.e("UmengManager","ff="+f.getName()+"   "+f.getType().getName());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //init 友盟
        UMConfigure.init(context, Contants.UMENG_APPKEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, Contants.UMENG_MESSAGE_SECRET);
        //UMConfigure.setLogEnabled(true);
        //Logger.e("UMConfigure  getInitStatus="+UMConfigure.getInitStatus());
        MobclickAgent.setDebugMode(true);
        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.setCatchUncaughtExceptions(true);
        handler = new Handler(context.getMainLooper());
        mPushAgent = PushAgent.getInstance(context);
        //sdk开启通知声音
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        mPushAgent.setMessageHandler(messageHandler);
        //使用自定义的NotificationHandler
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        mPushAgent.register(this);
    }

    @Override
    public void onDestroy() {
        mDevicetoken=null;
        mPushAgent=null;

    }

    public String getDevicetoken(){
        return mDevicetoken;
    }

    @Override
    public void onFailure(String s, String s1) {
        Log.e("UmengManager","UMConfigure  s="+s+"   s1="+s1);
    }

    @Override
    public void onSuccess(String devicetoken) {
          //注册成功会返回device token
        Log.e("UmengManager","UMConfigure devicetoken="+devicetoken);
        mDevicetoken=devicetoken;
    }

   private UmengMessageHandler messageHandler = new UmengMessageHandler() {

        /**
         * 通知的回调方法（通知送达时会回调）
         */
        @Override
        public void dealWithNotificationMessage(Context context, UMessage msg) {
            //调用super，会展示通知，不调用super，则不展示通知。
            super.dealWithNotificationMessage(context, msg);
        }

        /**
         * 自定义消息的回调方法
         */
        @Override
        public void dealWithCustomMessage(final Context context, final UMessage msg) {

            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    // 对自定义消息的处理方式，点击或者忽略
                    boolean isClickOrDismissed = true;
                    if (isClickOrDismissed) {
                        //自定义消息的点击统计
                        UTrack.getInstance(context.getApplicationContext()).trackMsgClick(msg);
                    } else {
                        //自定义消息的忽略统计
                        UTrack.getInstance(context.getApplicationContext()).trackMsgDismissed(msg);
                    }
                }
            });
        }

        /**
         * 自定义通知栏样式的回调方法
         */
        @Override
        public Notification getNotification(Context context, UMessage msg) {
            switch (msg.builder_id) {
                case 1:
                    Notification.Builder builder = new Notification.Builder(context);
                    RemoteViews myNotificationView = new RemoteViews(context.getPackageName(),
                            R.layout.notification_view);
                    myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                    myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                    myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                    myNotificationView.setImageViewResource(R.id.notification_small_icon,
                            getSmallIconId(context, msg));
                    builder.setContent(myNotificationView)
                            .setSmallIcon(getSmallIconId(context, msg))
                            .setTicker(msg.ticker)
                            .setAutoCancel(true);

                    return builder.getNotification();
                default:
                    //默认为0，若填写的builder_id并不存在，也使用默认。
                    return super.getNotification(context, msg);
            }
        }
    };

    /**
     * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
     * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
     * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
     * */
   private UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

        @Override
        public void launchApp(Context context, UMessage msg) {
            super.launchApp(context, msg);
        }

        @Override
        public void openUrl(Context context, UMessage msg) {
            super.openUrl(context, msg);
        }

        @Override
        public void openActivity(Context context, UMessage msg) {
            super.openActivity(context, msg);
        }

        @Override
        public void dealWithCustomAction(Context context, UMessage msg) {

        }
    };

}
